package com.meida.module.arc.client.utils;

import cn.hutool.core.io.FileUtil;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.utils.ApiAssert;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <b>功能名：ArcUtils</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2021-11-22 jiabing
 */
public class ArcUtils {
    private static String sysCodePrefix = "ABCDEFGHI";
    private static Integer defaultSysCodeLength = 3;
    //数字自动补零

    /**
     *
     * @param length 长度
     * @param number 数字
     * @return
     */
    public static String numberFormatStr(Integer length,Integer number){
        StringBuffer sb = new StringBuffer("%0");
        sb.append(length);
        sb.append("d");
        return String.format(sb.toString(),number);
    }

    /**
     *
     * @param parentSysCode 父编码
     * @param preSysCode 上一个兄弟编码
     * @return
     */
    public static String genNextSysCode(String parentSysCode,String preSysCode){
        StringBuffer sb = new StringBuffer();
        if(FlymeUtils.isEmpty(parentSysCode)&&FlymeUtils.isEmpty(preSysCode)){
            sb.append(sysCodePrefix.charAt(0));
            sb.append(numberFormatStr(defaultSysCodeLength-1,1));
            return sb.toString();
        }
        if(FlymeUtils.isNotEmpty(parentSysCode)){
            sb.append(parentSysCode);
        }
        if(FlymeUtils.isNotEmpty(preSysCode)){
            preSysCode = preSysCode.replace(parentSysCode==null?"":parentSysCode,"");
            sb.append(preSysCode.substring(0,1));
            sb.append(ArcUtils.numberFormatStr(defaultSysCodeLength-1,Integer.parseInt(preSysCode.substring(1))+1));
        }else{
            Character parentPrefixCode = null;
            for(int i=sysCodePrefix.length()-1;i>=0;i--){
                if(parentSysCode.indexOf(sysCodePrefix.charAt(i))>-1){
                    parentPrefixCode = sysCodePrefix.charAt(i);
                    break;
                }
            }
            if(parentPrefixCode==null){
                ApiAssert.failure("父级编码错误");
            }

            if(parentPrefixCode.equals(sysCodePrefix.charAt(sysCodePrefix.length()-1))){
                ApiAssert.failure(String.format("树形结构等级最大为%s级",sysCodePrefix.length()));
            }
            sb.append(sysCodePrefix.charAt((sysCodePrefix.indexOf(parentPrefixCode)+1)));
            sb.append(numberFormatStr(defaultSysCodeLength-1,1));
        }
        return sb.toString();
    }

    public static String getRootTempPath() {
        String path = ArcUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
//        if (System.getProperty("os.name").contains("dows")) {
//            path = path.substring(1,path.length());
//        }

        if (path.contains("jar")) {
            return path.substring(0,path.lastIndexOf("."));
            //return path.substring(0,path.lastIndexOf("/"));
        }

        return path.replace("target/classes/", "");
    }

    public static boolean checkCode(String code) {
        if (FlymeUtils.isEmpty(code)) {
            return false;
        }
        String reg = "^\\w{0,9}$";
        return code.matches(reg);
    }

    public static boolean isValidString(String code) {
        if (FlymeUtils.isEmpty(code)) {
            return false;
        }
        String pattern = "^[a-zA-Z0-9_]+$";
        return code.matches(pattern);
    }


    /**
     * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
     */
    public static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    public static String getMainBordId_windows() throws Exception {
        String result = "";
        File file = File.createTempFile("realhowto", ".vbs");
        file.deleteOnExit();
        FileWriter fw = new java.io.FileWriter(file);

        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_BaseBoard\") \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";

        fw.write(vbs);
        fw.close();
        Process p = Runtime.getRuntime().exec(
                "cscript //NoLogo " + file.getPath());
        BufferedReader input = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            result += line;
        }
        System.out.println("-------------"+line);
        input.close();
        return result.trim();
    }

    public static String getMainBordId_linux() throws Exception{

        String result = "";
        String maniBord_cmd = "dmidecode | grep 'Serial Number' | awk '{print $3}' | tail -1";
        Process p;
        p = Runtime.getRuntime().exec(
                new String[] { "sh", "-c", maniBord_cmd });// 管道
        BufferedReader br = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            result += line;
            break;
        }
        br.close();
        return result;
    }

    public static String getMainBordId() throws Exception {
        String os = getOSName();
        String mainBordId = "";
        System.out.println(os);
        if (os.startsWith("win")) {
            mainBordId = getMainBordId_windows();
        } else if (os.startsWith("linux")) {
            mainBordId = getMainBordId_linux();
        }
        if (FlymeUtils.isEmpty(mainBordId)) {
            mainBordId = null;
        }
        return mainBordId;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\\t|\\r|\\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static void main(String[] args) throws Exception {


        System.out.println(checkCode("123"));

        /*String tableNames = "arc_info10000, arc_info10001";
        String[] arr = tableNames.split(",");
        for (int i = 0; i < arr.length; i++) {
            System.out.println("ALTER TABLE " + arr[i].trim() + " ADD COLUMN refCount  int NULL DEFAULT 0 AFTER responsibleby;");
        }
        if (1 == 1) return;
        String str = "2022-01-02";
        Date dda = DateUtil.parse(str,"yyyy-MM-dd HH:mm:ss");
        System.out.println(dda);
        System.out.println(DateUtil.parse(str,"yyyy-MM-dd"));
        String mainBord = getMainBordId();
        System.out.println(mainBord);
        System.out.println(111);
        String fileName ="ss/sssdfsd.xls";
        String[] fileNameArr = fileName.split("\\.");
        System.out.println(fileNameArr.length);
        fileName = com.meida.common.utils.DateUtil.date2Str(new Date(),"yyyyMMddHHmmssSSS")+"."+fileNameArr[1];
        System.out.println(fileName);
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<4;i++){
            sb.insert(0,i);
        }
        System.out.println(sb.toString());
        List<ArcField> targetBatchRefFields = new ArrayList<>();
        ArcField f1 = new ArcField();
        f1.setFieldCnName("heihei");
        targetBatchRefFields.add(f1);
        targetBatchRefFields.add(f1);
        System.out.println(targetBatchRefFields.stream().map(item->{
            return item.getFieldCnName();
        }).collect(Collectors.joining("+")));

        if(1==1)return;
        ArcUtils.checkCode("23");
        ArcUtils.checkCode("23_sdA");
        ArcUtils.checkCode("023_sdA");
        ArcUtils.checkCode("_s dA");
        if(1==1)return;
        String cc = "[\"1\",\"2\"]";
        System.out.println(JsonUtils.json2list(cc,String.class).size());
        Long b = 0L;
        System.out.println(b==0);
        System.out.println(String.format("开通:%s%s%s%s天借阅时间."
                ,true?"原文浏览,":""
                ,true?"打印,":""
                ,true?"下载(1)次,":""
                ,null));

        if(1==1)return;
        Map<String,Object> arcParamMap = JsonUtils.jsonToBean("{\"1473189536445792261\":\"1\",\"1473189536454180871\":\"D10\",\"1473189536462569475\":\"哈哈嘿嘿\"}",Map.class);
        System.out.println(getRootTempPath());
        //System.out.println(aa.getClass().getClassLoader().getResource("").getPath());
        List<ArcNumFmt> arcNumFmt = JsonUtils.json2list("[{fieldName:\"unitId\",arcConnect:\"-\"}]", ArcNumFmt.class);
        arcNumFmt.forEach(obj->{
            System.out.println(obj);
        });
        String s = "2021-12-23";
        Date d = DateUtil.parse(s,"yyyy-MM-dd");
        System.out.println(d.toString());
        Object a = "0";
        System.out.println(CategoryTypeEnum.CATEGORY_TYPE_0.getCode().toString().equals(a.toString()));

        System.out.println(Math.pow(10,(ArchiveConstants.ARC_TABLE_PREFIX_LENGTH-1)));

//        File f = new File("E:\\myfile\\01 项目管理\\05 档案馆系统\\02 开发临时文件\\导入测试.xlsx");

        List<Map> re =  ExcelUtils.importExcel("E:\\myfile\\01 项目管理\\05 档案馆系统\\02 开发临时文件\\导入测试 - 副本.xlsx",0,1,Map.class);


        System.out.println(ArcUtils.numberFormatStr(3,3));


        System.out.println((int)Math.pow(10,(ArchiveConstants.ARC_TABLE_PREFIX_LENGTH-1)));
        System.out.println(Integer.parseInt("00001"));
        System.out.println(ArcUtils.genNextSysCode(null,null));
        System.out.println(ArcUtils.genNextSysCode(null,"A001"));
        System.out.println(ArcUtils.genNextSysCode("A001", null));
        System.out.println(ArcUtils.genNextSysCode("A001", "A001B087"));
        System.out.println(ArcUtils.genNextSysCode("A001", "A001B080"));
        System.out.println(ArcUtils.genNextSysCode("A001B080", "A001B080C001"));
//        System.out.println(ArcUtils.genNextSysCode("Q001",null));
        System.out.println(ArcUtils.genNextSysCode("A1B1C1D1E1F1G1H1I1", null));
*/

    }


    public static String execSql(String host, String port, String passwd, String filePath) {
        try {

            List<String> commands = new ArrayList<String>();
            if (FlymeUtils.isWindows()) {
                commands.add("cmd.exe");
                commands.add("/c");
                commands.add("mysql");
                commands.add("-h" + host);
                commands.add("-P" + port);
                commands.add("-uroot");
                commands.add("-p" + passwd);
                commands.add("archive_cloud");
                commands.add("<" + filePath);
                ProcessBuilder pb = new ProcessBuilder(commands);
                pb.redirectErrorStream(true);
                Process process = pb.start();
                IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
                process.destroy();
                FileUtil.del(filePath);
            } else {
                commands.add("bash");
                commands.add("-c");
                commands.add("mysql");
                ProcessBuilder pb = new ProcessBuilder();
                String command = "bash -c 'source /root/.bashrc && mysql -h" + host + " -P" + port + " -uroot -p" + passwd + " archive_cloud < " + filePath + "'";
                pb.command("sh", "-c", command);
                Process process = pb.start();
                // 等待命令执行完成
                process.waitFor();
                FileUtil.del(filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String execPGSql(String host, String port, String passwd, String filePath) {
        try {
            List<String> commands = new ArrayList<String>();
            commands.add("bash");
            commands.add("/c");
            commands.add("ksql");
            commands.add("\"host=" + host + " user=system password=system port=54321 dbname=archive_cloud\"");
            /*commands.add("-h " + host);
            commands.add("-p " + port);
            commands.add("-U system");
            commands.add("-W " + passwd);
            commands.add("-d archive_cloud");*/
            commands.add("-f " + filePath);

            System.out.println("****" + commands);
            ProcessBuilder pb = new ProcessBuilder(commands);
            pb.redirectErrorStream(true);
            //pb.environment().put("PGPASSWORD","system");
            Process process = pb.start();
            String result = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
            process.destroy();
            //FileUtil.del(filePath);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
